package org.itboys.weixin.tools;

import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.itboys.commons.utils.string.CommonStringUtils;
import org.itboys.weixin.dto.Article;
import org.itboys.weixin.dto.NewsMessage;
import org.itboys.weixin.dto.TextMessage;
import org.itboys.weixin.entity.WeixinMessageDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 * 消息解析相关
 * @author ChenJunhui
 *
 */
public class MessageUtils {
	
	private static  Logger logger = LoggerFactory.getLogger(MessageUtils.class);

	@SuppressWarnings("unchecked")
	public static Map<String, String> xmlToMap(HttpServletRequest request){
		// 从request中取得输入流
		InputStream is = null;
		try {
			is = request.getInputStream();
			SAXReader reader = new SAXReader();
			Document document = reader.read(is);
			// 得到xml根元素
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			//List<Element> elements = document.selectNodes(WeixinConstants.WEIXIN_ROOT_XPATH);
			Map<String, String> map = new HashMap<String, String>();
			for(Element ele:elements){
				map.put(ele.getName(), ele.getText());
			}
			return map;
		} catch (Exception e) {
			logger.error("message convert error");
			throw new RuntimeException(e);
		}finally{
			IOUtils.closeQuietly(is);
		}
	}
	
	
	/**
	 * 图文消息对象转换成xml
	 * 
	 * @param newsMessage 图文消息对象
	 * @return xml
	 */
	public static String newsMessageToXml(NewsMessage newsMessage) {
		xstream.alias("xml", newsMessage.getClass());
		xstream.alias("item", new Article().getClass());
		return xstream.toXML(newsMessage);
	}
	
	/**
	 * 文本消息对象转换成xml
	 * 
	 * @param textMessage 文本消息对象
	 * @return xml
	 */
	public static String textMessageToXml(TextMessage textMessage) {
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}
	
	/**
	 * 自己的微信消息详情 转图文
	 * @param messages
	 * @return
	 */
	public static List<Article> weixinMessageToArticles(List<WeixinMessageDetail> messages,String imgRoot){
		List<Article> articles = Lists.newArrayListWithCapacity(messages.size());
		for(WeixinMessageDetail message:messages){
			Article article = new Article();
			article.setTitle(CommonStringUtils.nullToEmpty(message.getTitle()));
			article.setDescription(CommonStringUtils.nullToEmpty(message.getContent()));
			if(null!=message.getImg()){
				article.setPicUrl(imgRoot+CommonStringUtils.nullToEmpty(message.getImg()));
			}
			article.setUrl(CommonStringUtils.nullToEmpty(message.getUrl()));
			articles.add(article);
		}
		return articles;
	}
	
	/**
	 * 扩展xstream，使其支持CDATA块
	 * 
	 * @date 2013-05-19
	 */
	private static XStream xstream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				
				boolean cdata = true;
				
				public void startNode(String name, @SuppressWarnings("rawtypes") Class clazz) {
					super.startNode(name);
				}

				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});
}
